package com.xuexiang.yoyo.sql.mapper;

import android.content.ContentValues;
import android.database.Cursor;

import com.xuexiang.yoyo.constant.HesAppStatic;
import com.xuexiang.yoyo.entity.KeyValue;

import java.util.ArrayList;
import java.util.List;

public class KeyValueMapper {
    public static final String TABLE = "key_value";
    public static final String CREATE_TABLE_SQL="CREATE TABLE "+ TABLE +"(key TEXT PRIMARY KEY,value TEXT);";

    public static String queryValueByKey(String key){
        Cursor cursor = HesAppStatic.getmDataBaseOpenHelper().query(TABLE, "where key='" + key + "'");
        String value = null;
        while (cursor.moveToNext()) {
            value = cursor.getString(1);
        }
        cursor.close();
        return value;
    }

    public static void insert(KeyValue keyValue){
        delete(keyValue.getKey());
        ContentValues deviceContentValues = new ContentValues();
        deviceContentValues.put("key", keyValue.getKey());
        deviceContentValues.put("value", keyValue.getValue());
        HesAppStatic.getmDataBaseOpenHelper().insert(TABLE,deviceContentValues);
    }
    public static void insert(String key,String value){
        KeyValue k = new KeyValue();
        k.setKey(key);
        k.setValue(value);
        insert(k);
    }
    public static void delete(){
        HesAppStatic.getmDataBaseOpenHelper().delete(TABLE,"",null);
    }
    public static void delete(String key){
        HesAppStatic.getmDataBaseOpenHelper().delete(TABLE,"key='"+key+"'",null);
    }
    public static List<KeyValue> queryAll(){
        Cursor cursor = HesAppStatic.getmDataBaseOpenHelper().query(TABLE, "");
        List<KeyValue> resultList = new ArrayList<>();
        while (cursor.moveToNext()) {
            KeyValue keyValue = new KeyValue();
            keyValue.setKey(cursor.getString(0));
            keyValue.setValue(cursor.getString(1));
            resultList.add(keyValue);
        }

        cursor.close();
        return resultList;
    }

}
